package login;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

// 用来处理登录请求
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || username.equals("") || password == null || password.equals("")) {
            // 参数不完整，直接返回到登录页面
            resp.getWriter().write("login.html");
            return;
        }
        if (!username.equals("zhangsan") || !password.equals("1234")) {
            // 登录失败
            resp.getWriter().write("用户名或密码错误，登录失败");
            return;
        }
        // 登录成功
        // 创建一个会话，将用户名和密码填写进去
        HttpSession session = req.getSession(true);
        session.setAttribute("username", "zhangsan");
        session.setAttribute("password", "1234");

        Integer visitCount = (Integer) session.getAttribute("visitCount");
        if (visitCount == null) {
            session.setAttribute("visitCount", 0);
        }

        // 让页面跳转到登录页面, 重定向跳转是 get 请求
        resp.sendRedirect("index");
    }
}
